package org.hugoduncan.appam.component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.abdera.model.Collection;
import org.apache.abdera.model.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hugoduncan.appam.model.EntryComponent;
import org.hugoduncan.appam.server.AppServletRequest;
import org.hugoduncan.appam.server.AppServletResponse;

public abstract class BaseCollection
{
    static final Log log = LogFactory.getLog(BaseCollection.class);

    protected Collection collection;

    private List<EntryComponent> entryComponents = new ArrayList<EntryComponent>();

    /**
     * location of the collection
     */
    protected String location = "/collection";

    public BaseCollection() {
        super();
    }

    public void add(EntryComponent entryComponent) {
        entryComponents.add(entryComponent);
    }

    public void setCollection(Collection collection) {
        this.collection = collection;
        try {
            location = collection.getHref().toString();
        } catch (URISyntaxException e) {
            log
                    .error("invalid href for collection "
                            + collection.getTitle(), e);
        }
    }

    public boolean process(AppServletRequest request,
            AppServletResponse response) throws IOException, ServletException {

        log.debug("BaseCollection processing " + request.getMethod()
                + " request to " + request.getPathInfo());

        // process entry components first, in case they have nested paths
        if (!request.getMethod().equals("POST")
                || request.getPathInfo().equals(location)) {
            for (EntryComponent component : entryComponents) {
                Entry entry = component.process(request, response);
                if (entry != null) {
                    updateFeed(request, response, entry);
                    return true;
                }
            }
        }

        if (request.getPathInfo().startsWith(location)) {
            processCollection(request, response);
            return true;
        }
        return false;
    }

    protected void processCollection(AppServletRequest request,
            AppServletResponse response) throws IOException, ServletException {
        if (request.getMethod().equals("GET")) {
            sendFeed(request, response);
        }
    }

    protected abstract void sendFeed(AppServletRequest request,
            AppServletResponse response) throws IOException;

    protected abstract void updateFeed(AppServletRequest request,
            AppServletResponse response, Entry entry) throws IOException;
}